﻿<div id="app" class="common-layout" style="max-width: max-content;">
    <div id="tableBlock">
        <!-- 查询区域 -->
        <div class="search-area">
            <!-- 查询条件 -->
            <div class="search-row">
                <div class="search-item">
                    <label>销售订单号：</label>
                    <el-input type="text" v-model="searchForm.salesOrderNo" class="formTableInput" placeholder="请输入销售订单号"></el-input>
                </div>
                <div class="search-item">
                    <label>单据状态：</label>
                    <el-select v-model="searchForm.orderStatus" class="formTableSelect" placeholder="请选择订单状态">
                        <el-option label="全部" value=""></el-option>
                        <el-option v-for="(config, key) in statusConfig" :key="key" :label="config.text" :value="key"></el-option>
                    </el-select>
                </div>
                <div class="search-item">
                    <label>客户：</label>
                    <el-select v-model="searchForm.customerName" class="formTableSelect" placeholder="请选择客户" filterable>
                        <el-option label="全部" value=""></el-option>
                        <el-option v-for="customer in customerOptions" :key="customer.id" :label="customer.name" :value="customer.name"></el-option>
                    </el-select>
                </div>
                <!-- 新增销售时间范围选择 -->
                <div class="search-item">
                    <label>销售时间：</label>
                    <el-date-picker v-model="searchForm.salesDateRange"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    value-format="YYYY-MM-DD"
                                    class="formTableSelect"
                                    style="width: 240px;">
                    </el-date-picker>
                </div>
                <el-button type="default" v-on:click="resetForm">重置</el-button>
                <el-button type="primary" v-on:click="searchTable">查询</el-button>
            </div>

            <!-- 操作按钮区域 -->
            <div class="buttonBlock">
                <el-button type="primary" v-on:click="addSalesOrder">新增</el-button>
                <el-button type="default" v-on:click="editSalesOrder">编辑</el-button>
                <el-button type="success"
                           v-on:click="batchAuditSalesOrder"
                           :disabled="selectedRows.length === 0">
                    审核
                </el-button>
                <el-button type="default" v-on:click="deleteSalesOrder">删除</el-button>
                <el-button type="default" v-on:click="copySalesOrder">复制</el-button>
                <el-button type="default" v-on:click="exportTable">导出</el-button>
                <el-button type="default" v-on:click="importSalesOrder">导入</el-button>
                <el-button type="success" v-on:click="refreshTable">刷新</el-button>
            </div>
        </div>

        <!-- 表格区域 -->
        <div class="btnAndTable">
            <el-table :data="paginatedData"
                      style="width: 100%; margin-top: 10px"
                      v-on:selection-change="handleSelectionChange"
                      ref="multipleTable"
                      stripe
                      border>
                <el-table-column fixed type="selection" width="50"></el-table-column>
                <el-table-column fixed label="销售订单号" width="150">
                    <template #default="scope">
                        <span style="color: #10b981; cursor: pointer;" v-on:click="jumpToDetail(scope.row)">
                            <span v-html="highlightText(scope.row.salesOrderNo, searchForm.salesOrderNo)"></span>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column fixed prop="orderStatus" label="单据状态" width="100">
                    <template #default="scope">
                        <span :class="['status-tag', getStatusClass(scope.row.orderStatus)]">
                            {{ getStatusText(scope.row.orderStatus) }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column fixed prop="salesDate" label="销售日期" width="120">
                    <template #default="scope">
                        {{ formatDate(scope.row.salesDate) }}
                    </template>
                </el-table-column>
                <el-table-column prop="customerName" label="客户名称" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.customerName, searchForm.customerName)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="contactPerson" label="联系人" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.contactPerson, searchForm.salesOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="contactPhon" label="联系方式" width="130">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.contactPhon, searchForm.salesOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="sellerShortName" label="销售部门" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.sellerShortName, searchForm.salesOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="sellerBy" label="销售负责人" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.sellerBy, searchForm.salesOrderNo)"></span>
                    </template>
                </el-table-column>

                <el-table-column prop="salesQuantity" label="销售数量" width="120"></el-table-column>
                <el-table-column prop="salesAmount" label="销售金额" width="120"></el-table-column>
                <el-table-column prop="goodsNamelist" label="销售货品" width="200">
                    <template #default="scope">
                        <el-tooltip v-if="scope.row.goodsNamelist && scope.row.goodsNamelist.length > 10"
                                    effect="dark"
                                    :content="scope.row.goodsNamelist"
                                    placement="top">
                            <span>{{ truncateText(scope.row.goodsNamelist, 10) }}</span>
                        </el-tooltip>
                        <span v-else>{{ scope.row.goodsNamelist || '-' }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="createBy" label="制单人" width="100">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.createBy, searchForm.salesOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="createShortName" label="所在部门" width="100">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.createShortName, searchForm.salesOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="制单时间" width="160">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="auditorBy" label="审核人" width="120">
                    <template #default="scope">
                        <span v-html="highlightText(scope.row.auditorBy, searchForm.salesOrderNo)"></span>
                    </template>
                </el-table-column>
                <el-table-column prop="auditorTime" label="审核时间" width="160">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.auditorTime) }}
                    </template>
                </el-table-column>

                <!-- 在操作列模板中添加审核按钮 -->
                <el-table-column fixed="right" label="操作" min-width="130">
                    <template #default="scope">
                        <!-- 1. 草稿(0)/待审核(1)状态：显示【编辑】【删除】 -->
                        <el-button v-if="scope.row.orderStatus === '0' || scope.row.orderStatus === '1'"
                                   class="operate-btn"
                                   link type="primary" size="default"
                                   v-on:click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button v-if="scope.row.orderStatus === '0' || scope.row.orderStatus === '1'"
                                   class="operate-btn"
                                   link type="danger" size="default"
                                   v-on:click="deleteSingleSalesOrder(scope.row)">
                            删除
                        </el-button>

                        <!-- 移除原操作列中的审核按钮 -->
                        <!-- 3. 已驳回(2)状态：显示【编辑】【撤销】 -->
                        <el-button v-if="scope.row.orderStatus === '2'"
                                   class="operate-btn"
                                   link type="primary" size="default"
                                   v-on:click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button v-if="scope.row.orderStatus === '2'"
                                   class="operate-btn"
                                   link type="warning" size="default"
                                   v-on:click="handleRejectCancel(scope.row)">
                            撤销
                        </el-button>

                        <!-- 4. 已审核(3)状态：显示【关闭】 -->
                        <el-button v-if="scope.row.orderStatus === '3'"
                                   class="operate-btn"
                                   link type="warning" size="default"
                                   v-on:click="closeSalesOrder(scope.row)">
                            关闭
                        </el-button>

                        <!-- 5. 已关闭(4)状态：显示【启用】 -->
                        <el-button v-if="scope.row.orderStatus === '8'"
                                   class="operate-btn"
                                   link type="success" size="default"
                                   v-on:click="enableSalesOrder(scope.row)">
                            启用
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage"
                           v-model:page-size="pageSize"
                           :page-sizes="[10, 20, 50, 100]"
                           :total="filteredData.length"
                           layout="total, sizes, prev, pager, next, jumper"
                           v-on:size-change="handleSizeChange"
                           v-on:current-change="handleCurrentChange">
            </el-pagination>
        </div>
    </div>
    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="销售订单审核" width="500px">
        <div style="padding: 20px;">
            <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: bold;">审核结果</label>
                <el-radio-group v-model="auditResult">
                    <el-radio label="通过" style="margin-right: 20px;">审核通过</el-radio>
                    <el-radio label="驳回">审核驳回</el-radio>
                </el-radio-group>
            </div>
            <div>
                <label style="display: block; margin-bottom: 8px; font-weight: bold;">审核意见</label>
                <el-input type="textarea"
                          v-model="auditOpinion"
                          rows="4"
                          placeholder="请输入审核意见（可选）"
                          maxlength="200"
                          show-word-limit></el-input>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button v-on:click="auditDialogVisible = false">取消</el-button>
                <el-button type="primary" v-on:click="submitAudit">确定</el-button>
            </div>
        </template>
    </el-dialog>
</div>

<script>
    const { createApp, ref, onMounted, computed } = Vue;
    const { ElMessageBox, ElMessage, ElNotification } = ElementPlus;

    // 将后端的状态数据传递给前端
    var statusList = @Html.Raw(Json.Serialize(ViewBag.TypeList));
    // 使用从后端获取的状态数据
    const STATUS_CONFIG = {};

    const app = createApp({
        setup() {

            // 根据状态值返回对应的样式类
            const getStatusClassByValue = (status) => {
                const classMap = {
                    '0': 'status-draft',
                    '1': 'status-pending',
                    '2': 'status-rejected',
                    '3': 'status-approved',
                    '4': 'status-closed',
                    '5': 'status-approved',
                    '6': 'status-closed'
                };
                return classMap[status] || '';
            };

            // 从后端获取状态数据
            if (typeof statusList !== 'undefined' && statusList) {
                statusList.forEach(item => {
                    STATUS_CONFIG[item.code] = {
                        text: item.name,
                        class: getStatusClassByValue(item.code) // 根据状态值返回对应的样式类
                    };
                });
            }
            const statusConfig = ref(STATUS_CONFIG);

            // -------------------------- 1. 基础数据初始化 --------------------------
            // 原始数据备份
            const originalData = ref([]);

            // 初始化加载数据
            const refreshData = async () => {
                try {
                    const response = await axios.post('/OmSalesOrder/GetAll');
                    if (response.data.code === 200) {
                        originalData.value = response.data.data.result;
                        tableData.value = [...originalData.value];
                        ElMessage.success('销售订单数据加载成功');
                    }
                } catch (error) {
                    console.error('加载出错:', error);
                    ElMessage.error('数据加载失败，请重试');
                }
            };

            // 加载客户选项
            const loadCustomerOptions = async () => {
                try {
                    const response = await axios.post('/OmSalesOrder/CustomerAll');
                    if (response.data.code === 200) {
                        customerOptions.value = response.data.data;
                    }
                } catch (error) {
                    console.error('加载客户选项出错:', error);
                }
            };

            // 搜索表单
            const searchForm = ref({
                salesOrderNo: '',
                customerName: '', // 改为客户名称查询
                orderStatus: '',
                salesDateRange: [] // 新增销售时间范围
            });

            // 客户选项
            const customerOptions = ref([]);

            // 表格数据
            const tableData = ref([]);

            // 选中行数据
            const selectedRows = ref([]);
            // 表格实例
            const multipleTable = ref(null);

            // -------------------------- 2. 前端查询逻辑 --------------------------
            // 过滤后的数据
            const filteredData = computed(() => {
                let result = tableData.value;

                // 销售订单号模糊查询（支持多字段搜索）
                if (searchForm.value.salesOrderNo) {
                    const keyword = searchForm.value.salesOrderNo.toLowerCase();
                    result = result.filter(item =>
                        (item.salesOrderNo && item.salesOrderNo.toLowerCase().includes(keyword)) ||
                        (item.contactPerson && item.contactPerson.toLowerCase().includes(keyword)) ||
                        (item.contactPhon && item.contactPhon.toLowerCase().includes(keyword)) ||
                        (item.sellerShortName && item.sellerShortName.toLowerCase().includes(keyword)) ||
                        (item.sellerBy && item.sellerBy.toLowerCase().includes(keyword)) ||
                        (item.goodsNamelist && item.goodsNamelist.toLowerCase().includes(keyword)) ||
                        (item.createBy && item.createBy.toLowerCase().includes(keyword)) ||
                        (item.createShortName && item.createShortName.toLowerCase().includes(keyword)) ||
                        (item.auditorBy && item.auditorBy.toLowerCase().includes(keyword))
                    );
                }

                // 客户查询 - 根据客户名称文字匹配
                if (searchForm.value.customerName) {
                    const customerName = searchForm.value.customerName.toLowerCase();
                    result = result.filter(item =>
                        item.customerName && item.customerName.toLowerCase().includes(customerName)
                    );
                }

                // 单据状态查询
                if (searchForm.value.orderStatus) {
                    result = result.filter(item => item.orderStatus === searchForm.value.orderStatus);
                }

                // 销售时间范围查询
                if (searchForm.value.salesDateRange && searchForm.value.salesDateRange.length === 2) {
                    const startDate = new Date(searchForm.value.salesDateRange[0]);
                    const endDate = new Date(searchForm.value.salesDateRange[1]);
                    endDate.setHours(23, 59, 59, 999); // 设置为当天的结束时间

                    result = result.filter(item => {
                        if (!item.salesDate) return false;
                        const salesDate = new Date(item.salesDate);
                        return salesDate >= startDate && salesDate <= endDate;
                    });
                }

                return result;
            });

            // -------------------------- 3. 分页逻辑 --------------------------
            const currentPage = ref(1);
            const pageSize = ref(10);
            const total = computed(() => filteredData.value.length);
            const paginatedData = computed(() => {
                const start = (currentPage.value - 1) * pageSize.value;
                const end = start + pageSize.value;
                return filteredData.value.slice(start, end);
            });

            const handleSizeChange = (val) => {
                pageSize.value = val;
                currentPage.value = 1;
            };

            const handleCurrentChange = (val) => {
                currentPage.value = val;
                if (multipleTable.value) {
                    multipleTable.value.clearSelection();
                    selectedRows.value = [];
                }
            };

            // -------------------------- 4. 关键字高亮方法 --------------------------
            const highlightText = (text, keyword) => {
                if (!text) return '';
                if (!keyword) return text;

                const str = String(text);
                const key = String(keyword);

                // 创建正则表达式，忽略大小写
                const regex = new RegExp(`(${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
                return str.replace(regex, '<span class="highlight-text">$1</span>');
            };

            // -------------------------- 5. 状态转换辅助方法 --------------------------
            // 根据状态值获取显示文字
            const getStatusText = (status) => {
                return STATUS_CONFIG[status]?.text || '未知状态';
            };

            // 根据状态值获取样式类
            const getStatusClass = (status) => {
                return STATUS_CONFIG[status]?.class || '';
            };

            // -------------------------- 6. 审核相关逻辑 --------------------------
            const auditDialogVisible = ref(false);
            const auditResult = ref('通过');
            const auditOpinion = ref('');
            const currentAuditRow = ref(null);
            const auditQueue = ref([]);
            const currentAuditIndex = ref(0);

            // 获取当前用户ID
            const getCurrentUserId = () => {
                const userStr = sessionStorage.getItem('YH');
                if (!userStr) {
                    ElMessage.warning('未检测到登录状态，请重新登录');
                    return '';
                }
                try {
                    const userObj = JSON.parse(userStr);
                    const userId = userObj?.id?.toString() || '';
                    if (!userId) {
                        ElMessage.warning('用户信息不完整，请重新登录');
                    }
                    return userId;
                } catch (error) {
                    console.error('解析用户信息失败：', error);
                    ElMessage.error('用户信息异常，请重新登录');
                    return '';
                }
            };

            // 批量审核入口
            const batchAuditSalesOrder = () => {
                if (selectedRows.value.length === 0) {
                    ElMessage({ type: 'warning', message: '请先选中需要审核的销售订单！' });
                    return;
                }

                // 筛选出待审核状态的订单
                const pendingAuditRows = selectedRows.value.filter(row => row.orderStatus === '1');
                if (pendingAuditRows.length === 0) {
                    ElMessage({ type: 'error', message: '选中的订单中没有待审核状态的订单！' });
                    return;
                }

                // 初始化审核队列
                auditQueue.value = pendingAuditRows;
                currentAuditIndex.value = 0;

                // 开始审核第一个订单
                startNextAudit();
            };

            // 开始下一个订单审核
            const startNextAudit = () => {
                if (currentAuditIndex.value < auditQueue.value.length) {
                    const currentRow = auditQueue.value[currentAuditIndex.value];
                    currentAuditRow.value = currentRow;
                    auditResult.value = '通过'; // 重置为默认值
                    auditOpinion.value = ''; // 清空审核意见
                    auditDialogVisible.value = true;
                } else {
                    // 所有订单审核完成
                    ElMessage.success(`批量审核完成！共审核${auditQueue.value.length}条订单`);
                    auditQueue.value = [];
                    currentAuditIndex.value = 0;
                    refreshData(); // 刷新数据
                    selectedRows.value = []; // 清空选中状态
                }
            };

            // 提交审核
            const submitAudit = async () => {
                if (!currentAuditRow.value) {
                    ElMessage.warning('请选择要审核的订单');
                    return;
                }

                const row = currentAuditRow.value;
                const newStatus = auditResult.value === '通过' ? '3' : '2'; // 通过→已审核，驳回→已驳回
                const usersId = getCurrentUserId();

                if (!usersId) {
                    ElMessage.error('无法获取用户信息，请重新登录');
                    return;
                }

                try {
                    // 调用审核接口 - 修正数据结构以匹配后端Auditor类
                    const response = await axios.post('/OmSalesOrder/UpdateAuditorComment', {
                        Id: row.salesOrderId, // 注意：这里改为大写I，与后端Auditor类的Id属性匹配
                        OrderStatus: newStatus, // 注意：这里改为大写O
                        AuditorComment: auditOpinion.value, // 注意：这里改为大写A
                        AuditorBy: usersId, // 注意：这里改为大写A
                        AuditorTime: new Date().toISOString() // 注意：这里改为大写A
                    });

                    if (response.data.code === 200) {
                        // 更新前端表格数据
                        const index = tableData.value.findIndex(item => item.salesOrderId === row.salesOrderId);
                        if (index !== -1) {
                            tableData.value[index].orderStatus = newStatus;
                            tableData.value[index].auditorBy = usersId;
                            tableData.value[index].auditorTime = new Date().toISOString();
                            tableData.value[index].auditorComment = auditOpinion.value;
                        }

                        ElMessage.success(`订单 ${row.salesOrderNo} 审核${auditResult.value}`);
                        auditDialogVisible.value = false;

                        // 审核索引+1，继续下一个
                        currentAuditIndex.value++;
                        // 延迟打开下一个审核窗口，提升用户体验
                        setTimeout(() => {
                            startNextAudit();
                        }, 500);
                    } else {
                        ElMessage.error(response.data.msg || '审核失败');
                    }
                } catch (error) {
                    console.error('审核接口请求失败:', error);
                    ElMessage.error('审核失败，请稍后重试');
                }
            };

            // 取消审核
            const cancelAudit = () => {
                auditDialogVisible.value = false;
                // 询问是否继续审核下一个
                ElMessageBox.confirm(
                    '是否要继续审核下一个订单？',
                    '确认取消',
                    {
                        confirmButtonText: '继续下一个',
                        cancelButtonText: '停止审核',
                        type: 'info'
                    }
                ).then(() => {
                    currentAuditIndex.value++;
                    startNextAudit();
                }).catch(() => {
                    // 取消后续审核
                    ElMessage.info('已停止批量审核');
                    auditQueue.value = [];
                    currentAuditIndex.value = 0;
                });
            };

            // -------------------------- 7. 核心操作方法 --------------------------
            // 7.1 选中行变化
            const handleSelectionChange = (val) => {
                selectedRows.value = val;
            };

            // 7.2 编辑（仅草稿0/待审核1/已驳回2可执行）
            const handleEdit = (row) => {
                const allowEditStatus = ['0', '1', '2'];
                if (!allowEditStatus.includes(row.orderStatus)) {
                    ElMessage({
                        type: 'error',
                        message: `当前「${getStatusText(row.orderStatus)}」状态不允许编辑！`
                    });
                    return;
                }
                ElNotification({
                    title: '编辑销售订单',
                    message: `编辑销售订单：${row.salesOrderNo}`,
                    type: 'info'
                });
                window.location.href = `/OmSalesOrder/Edit?id=${row.salesOrderId}`;
            };

            // 7.3 单行删除（仅草稿0/待审核1可执行）
            const deleteSingleSalesOrder = (row) => {
                if (row.orderStatus !== '0' && row.orderStatus !== '1') {
                    ElMessage({
                        type: 'error',
                        message: `当前「${getStatusText(row.orderStatus)}」状态不允许删除！`
                    });
                    return;
                }
                ElMessageBox.confirm(
                    `确定删除销售订单 "${row.salesOrderNo}" 吗？删除后不可恢复！`,
                    '警告',
                    { type: 'error' }
                ).then(async () => {
                    try {
                        const response = await axios.post(`/OmSalesOrder/Delete?id=${row.salesOrderId}`);
                        if (response.data.code === 200) {
                            tableData.value = tableData.value.filter(item => item.salesOrderId !== row.salesOrderId);
                            originalData.value = originalData.value.filter(item => item.salesOrderId !== row.salesOrderId);
                            ElMessage({ type: 'success', message: '删除成功！' });
                        } else {
                            ElMessage({ type: 'error', message: response.data.msg || '删除失败' });
                        }
                    } catch (error) {
                        console.error('删除出错:', error);
                        ElMessage({ type: 'error', message: '删除失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消删除' });
                });
            };

            // 7.4 撤销操作（仅已驳回2可执行）
            const handleRejectCancel = (row) => {
                if (row.orderStatus !== '2') {
                    ElMessage({
                        type: 'error',
                        message: `当前「${getStatusText(row.orderStatus)}」状态不允许撤销！`
                    });
                    return;
                }
                ElMessageBox.confirm(
                    `确定撤销驳回状态，将销售订单"${row.salesOrderNo}"恢复为「待审核」吗？`,
                    '确认撤销',
                    { type: 'warning' }
                ).then(async () => {
                    try {
                        // 使用状态变更接口
                        const response = await axios.post(`/OmSalesOrder/AuditorStatus?status=1&id=${row.salesOrderId}`);
                        if (response.data.success) {
                            row.orderStatus = '1';
                            row.auditorBy = '';
                            row.auditorTime = '';
                            row.auditorComment = '';
                            ElMessage({ type: 'success', message: '撤销成功！' });
                        } else {
                            ElMessage({ type: 'error', message: response.data.msg || '撤销失败' });
                        }
                    } catch (error) {
                        console.error('撤销出错:', error);
                        ElMessage({ type: 'error', message: '撤销失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消撤销' });
                });
            };

            // 7.5 关闭销售订单（仅已审核3可执行）
            const closeSalesOrder = (row) => {
                ElMessageBox.confirm(
                    `确定关闭销售订单"${row.salesOrderNo}"吗？`,
                    '确认关闭',
                    { type: 'warning' }
                ).then(async () => {
                    try {
                        // 使用状态变更接口
                        const response = await axios.post(`/OmSalesOrder/AuditorStatus?status=4&id=${row.salesOrderId}`);
                        if (response.data.success) {
                            row.orderStatus = '4';
                            ElMessage({ type: 'success', message: '销售订单已关闭！' });
                        } else {
                            ElMessage({ type: 'error', message: response.data.msg || '关闭失败' });
                        }
                    } catch (error) {
                        console.error('关闭出错:', error);
                        ElMessage({ type: 'error', message: '关闭失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消关闭' });
                });
            };

            // 7.6 启用销售订单（仅已关闭4可执行）
            const enableSalesOrder = (row) => {
                ElMessageBox.confirm(
                    `确定启用销售订单"${row.salesOrderNo}"吗？`,
                    '确认启用',
                    { type: 'info' }
                ).then(async () => {
                    try {
                        // 使用状态变更接口
                        const response = await axios.post(`/OmSalesOrder/AuditorStatus?status=3&id=${row.salesOrderId}`);
                        if (response.data.success) {
                            row.orderStatus = '3';
                            ElMessage({ type: 'success', message: '销售订单已启用！' });
                        } else {
                            ElMessage({ type: 'error', message: response.data.msg || '启用失败' });
                        }
                    } catch (error) {
                        console.error('启用出错:', error);
                        ElMessage({ type: 'error', message: '启用失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消启用' });
                });
            };

            // 7.7 批量删除（仅草稿0/待审核1可执行）
            const deleteSalesOrder = () => {
                if (selectedRows.value.length === 0) {
                    ElMessage({ type: 'warning', message: '请先选中需要删除的销售订单！' });
                    return;
                }
                const canDeleteRows = selectedRows.value.filter(row =>
                    row.orderStatus === '0' || row.orderStatus === '1'
                );
                if (canDeleteRows.length === 0) {
                    ElMessage({ type: 'error', message: '仅「草稿」或「待审核」状态的销售订单可删除！' });
                    return;
                }
                const deleteIds = canDeleteRows.map(row => row.salesOrderId);
                ElMessageBox.confirm(
                    `确定删除选中的 ${canDeleteRows.length} 条销售订单吗？`,
                    '警告',
                    { type: 'error' }
                ).then(async () => {
                    try {
                        for (const id of deleteIds) {
                            await axios.post(`/OmSalesOrder/Delete?id=${id}`);
                        }
                        tableData.value = tableData.value.filter(row => !deleteIds.includes(row.salesOrderId));
                        originalData.value = originalData.value.filter(row => !deleteIds.includes(row.salesOrderId));
                        ElMessage({ type: 'success', message: '删除成功！' });
                        selectedRows.value = [];
                    } catch (error) {
                        console.error('批量删除出错:', error);
                        ElMessage({ type: 'error', message: '删除失败，请重试' });
                    }
                }).catch(() => {
                    ElMessage({ type: 'info', message: '已取消删除' });
                });
            };

            // -------------------------- 8. 查询相关方法 --------------------------
            // 查询方法
            const searchTable = () => {
                currentPage.value = 1;
                ElMessage({
                    type: 'success',
                    message: `查询到 ${filteredData.value.length} 条数据！`
                });
            };

            // 重置表单
            const resetForm = () => {
                searchForm.value = {
                    salesOrderNo: '',
                    customerName: '', // 改为客户名称
                    orderStatus: '',
                    salesDateRange: []
                };
                tableData.value = [...originalData.value];
                currentPage.value = 1;
                ElMessage({ type: 'success', message: '查询条件已重置！' });
            };

            // -------------------------- 9. 其他辅助方法 --------------------------
            // 日期格式化
            const formatDateTime = (date) => {
                if (!date) return '';
                const dt = new Date(date);
                const year = dt.getFullYear();
                const month = String(dt.getMonth() + 1).padStart(2, '0');
                const day = String(dt.getDate()).padStart(2, '0');
                const hours = String(dt.getHours()).padStart(2, '0');
                const minutes = String(dt.getMinutes()).padStart(2, '0');
                const seconds = String(dt.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            };

            // 日期格式化（仅日期）
            const formatDate = (date) => {
                if (!date) return '';
                const dt = new Date(date);
                const year = dt.getFullYear();
                const month = String(dt.getMonth() + 1).padStart(2, '0');
                const day = String(dt.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };

            // 销售订单号点击跳转页面
            const jumpToDetail = (row) => {
                ElMessage({ type: 'info', message: `跳转至销售订单${row.salesOrderNo}的详情页` });
                window.location.href = `/OmSalesOrder/Details?id=${row.salesOrderId}&pwd=114514`;
            };

            // 导出
            const exportTable = () => {
                ElMessage({ type: 'success', message: '导出请求已触发，正在下载...' });
            };

            // 刷新
            const refreshTable = () => {
                if (multipleTable.value) {
                    multipleTable.value.clearSelection();
                    selectedRows.value = [];
                }
                currentPage.value = 1;
                refreshData(); // 重新加载数据
                ElMessage({ type: 'success', message: '表格已刷新！' });
            };

            // 新增
            const addSalesOrder = () => {
                ElNotification({ title: '提示', message: '跳转至新增销售订单页面', type: 'info' });
                window.location.href = '/OmSalesOrder/Create';
            };

            // 复制
            const copySalesOrder = () => {
                if (selectedRows.value.length === 0) {
                    ElMessage({ type: 'warning', message: '请先选中需要复制的销售订单！' });
                    return;
                }
                if (selectedRows.value.length > 1) {
                    ElMessage({ type: 'warning', message: '仅支持单条销售订单复制！' });
                    return;
                }
                const targetRow = selectedRows.value[0];
                ElNotification({ title: '复制销售订单', message: `开始复制销售订单：${targetRow.salesOrderNo}`, type: 'info' });
            };

            // 编辑（批量选择）
            const editSalesOrder = () => {
                if (selectedRows.value.length === 0) {
                    ElMessage({ type: 'warning', message: '请先选中需要编辑的销售订单！' });
                    return;
                }
                if (selectedRows.value.length > 1) {
                    ElMessage({ type: 'warning', message: '仅支持单条销售订单编辑！' });
                    return;
                }
                const targetRow = selectedRows.value[0];
                handleEdit(targetRow);
            };

            // 导入
            const importSalesOrder = () => {
                ElNotification({ title: '导入销售订单', message: '打开销售订单导入窗口', type: 'info' });
            };
                // 文本截断方法
    const truncateText = (text, maxLength) => {
        if (!text) return '-';
        if (text.length <= maxLength) return text;
        return text.substring(0, maxLength) + '...';
    };
            // 页面挂载
            onMounted(() => {
                refreshData();
                loadCustomerOptions();
            });

            // 暴露数据和方法
            return {
                // 搜索表单
                searchForm,
                customerOptions,
    truncateText,

                // 表格相关
                tableData,
                paginatedData,
                filteredData,
                selectedRows,
                multipleTable,
                handleSelectionChange,
                handleEdit,
                deleteSingleSalesOrder,
                handleRejectCancel,
                closeSalesOrder,
                enableSalesOrder,
                getStatusText,
                getStatusClass,

                // 分页相关
                currentPage,
                pageSize,
                total,
                handleSizeChange,
                handleCurrentChange,

                // 审核相关
                auditDialogVisible,
                auditResult,
                auditOpinion,
                batchAuditSalesOrder,
                submitAudit,
                cancelAudit,

                // 高亮相关
                highlightText,

                // 按钮方法
                addSalesOrder,
                editSalesOrder,
                deleteSalesOrder,
                copySalesOrder,
                importSalesOrder,
                exportTable,
                refreshTable,
                resetForm,
                searchTable,
                formatDateTime,
                formatDate,
                jumpToDetail,
                statusConfig,
            };
        }
    });
    app.use(ElementPlus, {
       locale: ElementPlusLocaleZhCn
    });
    app.mount('#app');
</script>
<style>
    body {
        margin: 0;
        padding: 0;
        font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
        background-color: #f5f7fa;
    }

    #tableBlock {
        margin: 20px auto;
        width: 100%;
        max-width: max-content;
        padding-bottom: 20px;
        box-shadow: 0 0 10px 4px rgba(0, 0, 0, 0.1);
        background-color: #fff;
        border-radius: 6px;
    }

    .search-area {
        padding: 20px;
        border-bottom: 0px solid #ebeef5;
    }

    .formTableInput, .formTableSelect {
        display: inline-block;
        width: 180px;
    }

    .buttonBlock {
        height: 40px;
        width: 100%;
        padding: 20px;
        gap: 10px;
        margin-bottom: 15px;
        flex-wrap: wrap;
    }

    .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
        padding: 0 20px;
    }

    .audit-textarea {
        margin-top: 15px;
        width: 100%;
    }

    /* 操作列按钮间距 */
    .operate-btn {
        margin-right: 8px;
    }

    .btnAndTable {
        margin: 0 auto;
        padding: 0 20px;
    }

    .search-row {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 15px;
    }

    .search-item {
        display: flex;
        align-items: center;
    }

        .search-item label {
            min-width: 80px;
            text-align: right;
            margin-right: 10px;
        }

    .status-tag {
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
    }

    .status-draft {
        background-color: #f0f0f0;
        color: #666;
    }

    .status-pending {
        background-color: #e6f7ff;
        color: #1890ff;
    }

    .status-rejected {
        background-color: #fff2f0;
        color: #ff4d4f;
    }

    .status-approved {
        background-color: #f6ffed;
        color: #52c41a;
    }

    .status-closed {
        background-color: #f5f5f5;
        color: #8c8c8c;
    }

    /* 新增关键字高亮样式 */
    .highlight-text {
        background-color: #ffeb3b;
        color: #ff0000;
        font-weight: bold;
        padding: 1px 2px;
        border-radius: 2px;
    }
</style>